package com.zjy.financialsystemjavafx.controller;

import com.zjy.financialsystemjavafx.model.entity.Loan;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
import com.zjy.financialsystemjavafx.service.LoanService;
import com.zjy.financialsystemjavafx.util.SessionContext;
import javafx.scene.control.TextInputDialog;
import javafx.scene.control.ChoiceDialog;
import java.time.LocalDate;
import java.util.Optional;
import java.util.Arrays;

import java.io.IOException;

/**
 * 借贷管理控制器
 */
public class LoanController {

    @FXML
    private TableView<Loan> loanTable;

    @FXML
    private TableColumn<Loan, Integer> idColumn;

    @FXML
    private TableColumn<Loan, String> typeColumn;

    @FXML
    private TableColumn<Loan, Double> amountColumn;

    @FXML
    private TableColumn<Loan, Double> rateColumn;

    @FXML
    private TableColumn<Loan, LocalDate> startDateColumn;

    @FXML
    private TableColumn<Loan, LocalDate> dueDateColumn;

    @FXML
    private TableColumn<Loan, String> contactColumn;

    @FXML
    private TableColumn<Loan, String> infoColumn;

    @FXML
    private TableColumn<Loan, String> statusColumn;

    @FXML
    private TableColumn<Loan, String> descColumn;

    @FXML
    private Button addButton;

    @FXML
    private Button editButton;

    @FXML
    private Button deleteButton;

    @FXML
    private Button repayButton;

    @FXML
    private Button backButton;

    private final ObservableList<Loan> loanList = FXCollections.observableArrayList();
    private LoanService loanService;
    private int userId;

    @FXML
    private void initialize() {
        // 初始化服务和用户ID
        loanService = new LoanService();
        userId = SessionContext.getCurrentUser().getUserId();

        // 配置列
        idColumn.setCellValueFactory(new PropertyValueFactory<>("loanId"));
        typeColumn.setCellValueFactory(new PropertyValueFactory<>("loanType"));
        amountColumn.setCellValueFactory(new PropertyValueFactory<>("amount"));
        rateColumn.setCellValueFactory(new PropertyValueFactory<>("interestRate"));
        startDateColumn.setCellValueFactory(new PropertyValueFactory<>("startDate"));
        dueDateColumn.setCellValueFactory(new PropertyValueFactory<>("dueDate"));
        contactColumn.setCellValueFactory(new PropertyValueFactory<>("contactPerson"));
        infoColumn.setCellValueFactory(new PropertyValueFactory<>("contactInfo"));
        statusColumn.setCellValueFactory(new PropertyValueFactory<>("status"));
        descColumn.setCellValueFactory(new PropertyValueFactory<>("description"));

        // 绑定列表并刷新数据
        loanTable.setItems(loanList);
        refreshTable();
    }

    /**
     * 刷新借贷列表
     */
    private void refreshTable() {
        try {
            loanList.clear();
            loanList.addAll(loanService.getLoans(userId));
            System.out.println("[DEBUG] Loans loaded: " + loanList.size());
        } catch (Exception e) {
            e.printStackTrace();
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setTitle("加载错误");
            alert.setHeaderText(null);
            alert.setContentText("无法加载借贷数据: " + e.getMessage());
            alert.showAndWait();
        }
    }

    @FXML
    private void handleAdd(ActionEvent event) {
        try {
            // 借贷类型
            ChoiceDialog<String> typeDialog = new ChoiceDialog<>("Borrow", Arrays.asList("Borrow", "Lend"));
            typeDialog.setTitle("添加借贷");
            typeDialog.setHeaderText(null);
            typeDialog.setContentText("请选择借贷类型：");
            Optional<String> typeOpt = typeDialog.showAndWait();
            if (!typeOpt.isPresent()) return;
            String loanType = typeOpt.get();

            // 金额
            TextInputDialog amtDialog = new TextInputDialog();
            amtDialog.setTitle("添加借贷");
            amtDialog.setHeaderText(null);
            amtDialog.setContentText("请输入金额：");
            Optional<String> amtOpt = amtDialog.showAndWait();
            if (!amtOpt.isPresent()) return;
            double amount = Double.parseDouble(amtOpt.get());

            // 利率
            TextInputDialog rateDialog = new TextInputDialog("0.0");
            rateDialog.setTitle("添加借贷");
            rateDialog.setHeaderText(null);
            rateDialog.setContentText("请输入利率（%）：");
            Optional<String> rateOpt = rateDialog.showAndWait();
            double interestRate = rateOpt.map(Double::parseDouble).orElse(0.0);

            // 开始日期
            TextInputDialog startDialog = new TextInputDialog(LocalDate.now().toString());
            startDialog.setTitle("添加借贷");
            startDialog.setHeaderText(null);
            startDialog.setContentText("请输入开始日期（YYYY-MM-DD）：");
            Optional<String> startOpt = startDialog.showAndWait();
            if (!startOpt.isPresent()) return;
            LocalDate startDate = LocalDate.parse(startOpt.get());

            // 到期日期
            TextInputDialog dueDialog = new TextInputDialog(LocalDate.now().plusMonths(1).toString());
            dueDialog.setTitle("添加借贷");
            dueDialog.setHeaderText(null);
            dueDialog.setContentText("请输入到期日期（YYYY-MM-DD）：");
            Optional<String> dueOpt = dueDialog.showAndWait();
            if (!dueOpt.isPresent()) return;
            LocalDate dueDate = LocalDate.parse(dueOpt.get());

            // 联系人
            TextInputDialog personDialog = new TextInputDialog();
            personDialog.setTitle("添加借贷");
            personDialog.setHeaderText(null);
            personDialog.setContentText("请输入联系人：");
            String contactPerson = personDialog.showAndWait().orElse("");

            // 联系方式
            TextInputDialog infoDialog = new TextInputDialog();
            infoDialog.setTitle("添加借贷");
            infoDialog.setHeaderText(null);
            infoDialog.setContentText("请输入联系方式：");
            String contactInfo = infoDialog.showAndWait().orElse("");

            // 状态
            ChoiceDialog<String> statusDialog = new ChoiceDialog<>("Ongoing", Arrays.asList("Ongoing", "Closed"));
            statusDialog.setTitle("添加借贷");
            statusDialog.setHeaderText(null);
            statusDialog.setContentText("请选择状态：");
            String status = statusDialog.showAndWait().orElse("Ongoing");

            // 描述
            TextInputDialog descDialog = new TextInputDialog();
            descDialog.setTitle("添加借贷");
            descDialog.setHeaderText(null);
            descDialog.setContentText("请输入描述：");
            String desc = descDialog.showAndWait().orElse("");

            // 添加借贷记录
            boolean ok = loanService.addLoan(userId, loanType, amount, interestRate,
                    startDate, dueDate, contactPerson, contactInfo, status, desc);
            if (ok) refreshTable();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @FXML
    private void handleEdit(ActionEvent event) {
        Loan selected = loanTable.getSelectionModel().getSelectedItem();
        if (selected == null) {
            showSelectWarning();
            return;
        }
        try {
            // 借贷类型
            ChoiceDialog<String> typeDialog2 = new ChoiceDialog<>(selected.getLoanType(), Arrays.asList("Borrow", "Lend"));
            typeDialog2.setTitle("编辑借贷");
            typeDialog2.setHeaderText(null);
            typeDialog2.setContentText("请选择借贷类型：");
            Optional<String> typeOpt2 = typeDialog2.showAndWait();
            if (typeOpt2.isPresent()) selected.setLoanType(typeOpt2.get());

            // 金额
            TextInputDialog amtDialog2 = new TextInputDialog(String.valueOf(selected.getAmount()));
            amtDialog2.setTitle("编辑借贷");
            amtDialog2.setHeaderText(null);
            amtDialog2.setContentText("请输入金额：");
            Optional<String> amtOpt2 = amtDialog2.showAndWait();
            if (amtOpt2.isPresent()) selected.setAmount(Double.parseDouble(amtOpt2.get()));

            // 利率
            TextInputDialog rateDialog2 = new TextInputDialog(String.valueOf(selected.getInterestRate()));
            rateDialog2.setTitle("编辑借贷");
            rateDialog2.setHeaderText(null);
            rateDialog2.setContentText("请输入利率（%）：");
            Optional<String> rateOpt2 = rateDialog2.showAndWait();
            if (rateOpt2.isPresent()) selected.setInterestRate(Double.parseDouble(rateOpt2.get()));

            // 开始日期
            TextInputDialog startDialog2 = new TextInputDialog(selected.getStartDate().toString());
            startDialog2.setTitle("编辑借贷");
            startDialog2.setHeaderText(null);
            startDialog2.setContentText("请输入开始日期（YYYY-MM-DD）：");
            Optional<String> startOpt2 = startDialog2.showAndWait();
            if (startOpt2.isPresent()) selected.setStartDate(LocalDate.parse(startOpt2.get()));

            // 到期日期
            TextInputDialog dueDialog2 = new TextInputDialog(selected.getDueDate().toString());
            dueDialog2.setTitle("编辑借贷");
            dueDialog2.setHeaderText(null);
            dueDialog2.setContentText("请输入到期日期（YYYY-MM-DD）：");
            Optional<String> dueOpt2 = dueDialog2.showAndWait();
            if (dueOpt2.isPresent()) selected.setDueDate(LocalDate.parse(dueOpt2.get()));

            // 联系人
            TextInputDialog personDialog2 = new TextInputDialog(selected.getContactPerson());
            personDialog2.setTitle("编辑借贷");
            personDialog2.setHeaderText(null);
            personDialog2.setContentText("请输入联系人：");
            selected.setContactPerson(personDialog2.showAndWait().orElse(selected.getContactPerson()));

            // 联系方式
            TextInputDialog infoDialog2 = new TextInputDialog(selected.getContactInfo());
            infoDialog2.setTitle("编辑借贷");
            infoDialog2.setHeaderText(null);
            infoDialog2.setContentText("请输入联系方式：");
            selected.setContactInfo(infoDialog2.showAndWait().orElse(selected.getContactInfo()));

            // 状态
            ChoiceDialog<String> statusDialog2 = new ChoiceDialog<>(selected.getStatus(), Arrays.asList("Ongoing", "Closed"));
            statusDialog2.setTitle("编辑借贷");
            statusDialog2.setHeaderText(null);
            statusDialog2.setContentText("请选择状态：");
            selected.setStatus(statusDialog2.showAndWait().orElse(selected.getStatus()));

            // 描述
            TextInputDialog descDialog2 = new TextInputDialog(selected.getDescription());
            descDialog2.setTitle("编辑借贷");
            descDialog2.setHeaderText(null);
            descDialog2.setContentText("请输入描述：");
            selected.setDescription(descDialog2.showAndWait().orElse(selected.getDescription()));

            // 更新借贷记录
            boolean ok2 = loanService.updateLoan(selected);
            if (ok2) refreshTable();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @FXML
    private void handleDelete(ActionEvent event) {
        Loan selected = loanTable.getSelectionModel().getSelectedItem();
        if (selected == null) {
            showSelectWarning();
            return;
        }
        try {
            boolean ok = loanService.deleteLoan(selected.getLoanId());
            if (ok) refreshTable();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @FXML
    private void handleRepay(ActionEvent event) {
        Loan selected = loanTable.getSelectionModel().getSelectedItem();
        if (selected == null) {
            showSelectWarning();
            return;
        }
        TextInputDialog dialog = new TextInputDialog();
        dialog.setTitle("还款");
        dialog.setHeaderText("输入还款金额");
        Optional<String> result = dialog.showAndWait();
        if (result.isPresent()) {
            try {
                double amt = Double.parseDouble(result.get());
                boolean ok = loanService.addRepayment(selected.getLoanId(), amt, LocalDate.now(), "");
                if (ok) refreshTable();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @FXML
    private void handleBack(ActionEvent event) {
        try {
            Parent root = FXMLLoader.load(getClass().getResource("/com/zjy/financialsystemjavafx/view/Dashboard.fxml"));
            Stage stage = (Stage) loanTable.getScene().getWindow();
            stage.setTitle("个人财务管家 - 仪表盘");
            stage.setScene(new Scene(root));
            stage.show();
        } catch (IOException e) {
            e.printStackTrace();
            Alert alert = new Alert(AlertType.ERROR);
            alert.setTitle("加载错误");
            alert.setHeaderText(null);
            alert.setContentText("无法加载仪表盘界面");
            alert.showAndWait();
        }
    }

    private void showSelectWarning() {
        Alert alert = new Alert(AlertType.WARNING);
        alert.setTitle("未选择");
        alert.setHeaderText(null);
        alert.setContentText("请先选择一条借贷记录");
        alert.showAndWait();
    }
} 